export default {
    bind(el) {
        const dialogHeaderEl = el.querySelector('.el-dialog__header');
        const dragDom = el.querySelector('.el-dialog');

        if (!dialogHeaderEl || !dragDom) return;

        dialogHeaderEl.style.cursor = 'move';
        dragDom.style.position = 'fixed'; // 使用 fixed 定位
        dragDom.style.margin = '0';
        dragDom.style.transform = 'none';

        // ✅ 设置初始位置：顶部50px + 水平居中
        const setInitialPosition = () => {
            const windowWidth = window.innerWidth;
            const dialogWidth = dragDom.offsetWidth;
            
            // 计算水平居中位置
            // const left = Math.max(0, (windowWidth - dialogWidth) / 2);
            const top = 0; // 固定顶部50px
            
            dragDom.style.left = `500px`;
            dragDom.style.top = `${top}px`;
        };

        // 确保DOM渲染完成后设置位置
        setTimeout(setInitialPosition, 0);
        
        // ✅ 拖拽功能
        dialogHeaderEl.onmousedown = (e) => {
            // 获取当前弹窗位置
            const currentLeft = parseFloat(dragDom.style.left) || 0;
            const currentTop = parseFloat(dragDom.style.top) || 0;
            
            // 鼠标初始位置
            const startX = e.pageX;
            const startY = e.pageY;
            
            // 边界保护（防止拖出视口）
            const maxLeft = window.innerWidth - dragDom.offsetWidth;
            const maxTop = window.innerHeight - dragDom.offsetHeight;

            const move = (e) => {
                // 计算移动距离
                let deltaX = e.pageX - startX;
                let deltaY = e.pageY - startY;
                
                // 计算新位置（带边界检查）
                let newLeft = currentLeft + deltaX;
                let newTop = currentTop + deltaY;
                
                // 确保不会拖出视口
                newLeft = Math.max(0, Math.min(newLeft, maxLeft));
                newTop = Math.max(0, Math.min(newTop, maxTop));
                
                dragDom.style.left = `${newLeft}px`;
                dragDom.style.top = `${newTop}px`;
            };

            const up = () => {
                document.removeEventListener('mousemove', move);
                document.removeEventListener('mouseup', up);
            };

            document.addEventListener('mousemove', move);
            document.addEventListener('mouseup', up);
        };
    }
};